<?php
namespace app\admin\service;

use app\common\model\OperateModel;
use app\common\model\ProtectModel;
use app\common\model\StationModel;
use app\common\model\TemplateModel;
use app\common\model\UserModel;

class ProtectService
{
    private static $model;
    private static $stationModel;
    private static $userModel;
    private static $templateModel;
    private static $operateModel;

    public function __construct(ProtectModel $protectModel, StationModel $stationModel, UserModel $userModel, TemplateModel $templateModel, OperateModel $operateModel)
    {
        self::$model         = $protectModel;
        self::$stationModel  = $stationModel;
        self::$userModel     = $userModel;
        self::$templateModel = $templateModel;
        self::$operateModel  = $operateModel;
    }

    /**
     *
     * User: zhouyao
     * Date: 2018/12/1
     * Time: 6:15 PM
     * @param $params
     * @return mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index($params)
    {
        if (empty($params) || !isset($params['limit']) || !isset($params['page'])) {
            return app_fail(9997);
        }

        $where = [];
        $whereIn = [];
        if (!empty($params['charge_name'])) {
            $where['res_code'] = $params['charge_name'];
        }

        // 查询当前用户是普通还是超级管理员
        $user = self::$userModel->where('id', '=', $params['guid'])->find();
        if ($user['type'] > 1) {
            // 查询是否有指定的保护
            $operateList = self::$operateModel->where('user_id', '=', $user['id'])
                ->where('res_code', '<>', '')
                ->field('res_code')
                ->select()->toArray();
            $whereIn = array_column($operateList, 'res_code');
            $where['user_id'] = $params['guid'];
        } else {
            $protect = self::$model->field('res_code')->select()->toArray();
            $whereIn = array_column($protect, 'res_code');
        }

        $count = self::$model->where($where)->whereOr(function($query) use ($whereIn) {
            $query->whereIn('res_code', $whereIn);
        })->count();
        if ($count < 1) {
            return ['data' => [], 'count' => (int) $count];
        }

        $result     = self::$model->where($where)->whereOr(function($query) use ($whereIn) {
            $query->whereIn('res_code', $whereIn);
        })->page($params['page'], $params['limit'])->select();
        $stationArr = $result->column('station_id');
        $userArr    = $result->column('user_id');

        $station = self::$stationModel->whereIn('id', $stationArr)->column('station_name', 'id');
        $user    = self::$userModel->whereIn('id', $userArr)->column('nickname', 'id');

        $result->each(function ($item) use ($station, $user) {
            $item->station_name = isset($station[$item->station_id]) ? $station[$item->station_id] : '--';
            $item->nickname     = isset($user[$item->user_id]) ? $user[$item->user_id] : '--';
            $item->create_time  = date('Y-m-d', $item->create_time);
            return $item;
        });

        return ['data' => $result, 'count' => (int) $count];
    }

    /**
     * 查看指定保护下对应的模板
     * User: zhouyao
     * Date: 2018/12/4
     * Time: 3:01 PM
     * @param $params
     * @return mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function template($params)
    {
        if (empty($params) || !isset($params['code'])) {
            return app_fail(9997);
        }
        $params['page'] = 1;
        $params['limit'] = 100;
        $where = ['res_code' => $params['code']];
        $count = self::$templateModel->where($where)->count();
        if ($count < 1) {
            return ['data' => [], 'count' => $count];
        }

        $result  = self::$templateModel->where($where)
            ->page($params['page'], $params['limit'])
            ->select();
        $userArr = $result->column('user_id');
        $user    = self::$userModel->whereIn('id', $userArr)->column('nickname', 'id');

        $result->each(function ($item) use ($user) {
            $item->nickname = isset($user[$item->user_id]) ? $user[$item->user_id] : '--';
            return $item;
        });

        return ['data' => $result, 'count' => $count];
    }

    /**
     * 删除指定保护下面的测试模板
     * User: zhouyao
     * Date: 2018/12/4
     * Time: 3:12 PM
     * @param $params
     * @return mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function deleteTemplate($params)
    {
        if (empty($params) || !isset($params['id'])) {
            return app_fail(9997);
        }

        $row = self::$templateModel->where(['id' => $params['id']])->find();
        if (empty($row)) {
            return app_fail(9977);
        }

        // 查询用户类型
//        $user = self::$userModel->where(['id' => $params['guid']])->find();
//        if ($user['type'] != 1 && $user['id'] != $row['user_id']) {
//            return app_fail(1000);
//        }

        try {
            self::$templateModel->where(['id' => $params['id']])->delete();
            return true;
        } catch (\Exception $e) {
            return app_fail(9980);
        }
    }

    /**
     * 获取所有变电站信息
     * User: zhouyao
     * Date: 2018/12/7
     * Time: 2:57 PM
     * @param $params
     * @return mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function stationList($params)
    {
        if (empty($params)) {
            return app_fail(9997);
        }

        $stationList = self::$stationModel->field(['id', 'station_name'])->select();

        return $stationList;
    }

    /**
     * 更改保护的变电站信息
     * User: zhouyao
     * Date: 2018/12/4
     * Time: 3:25 PM
     * @param $params
     * @return mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updateStation($params)
    {
        if (empty($params) || !isset($params['guid']) || !isset($params['protect_id']) || !isset($params['station_id'])) {
            return app_fail(9997);
        }

        $row = self::$model->where('id', '=', $params['protect_id'])->find();

        $user = self::$userModel->where('id', '=', $params['guid'])->find();
        if ($user['type'] != 1 && $user['id'] != $row['user_id']) {
            return app_fail(1000);
        }

        try {
            $row->allowField(true)->save($params, ['id' => $params['protect_id']]);
            return true;
        } catch (\Exception $e) {
            return app_fail(9980);
        }
    }

    /**
     * 复制模板到其它空保护下
     * User: zhouyao
     * Date: 2018/12/4
     * Time: 4:26 PM
     * @param $params
     * @return mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updateTemplate($params)
    {
        if (empty($params) || !isset($params['guid'])) {
            return app_fail(9997);
        }

        // 查询当前保护信息与模板信息
        $protectTemp = self::$templateModel->where(['id' => $params['id']])->find();
        $protect = self::$model->where(['res_code' => $protectTemp['res_code']])->find();

        // 查询新增保护的信息
        $protectTwo = self::$model->where(['id' => $params['id_two']])->find();
        $protectTwoTemp = self::$templateModel->where(['res_code' => $protectTwo['res_code']])->find();
        $ext = self::$templateModel->where(['res_code' => $protectTwo['res_code'], 'template_name' => $protectTemp['template_name']])->find();
        if ($ext) {
            return app_fail(9976);
        }
        

        try {
            self::$templateModel->create([
                'res_code' => $protectTwo['res_code'],
                'template_name' => $protectTemp['template_name'],
                'template_proto' => $protectTemp['template_proto'],
                'user_id' => $protectTwo['user_id'],
                'remark' => $protectTemp['remark'],
                'create_time' => time(),
                'update_time' => time()
            ]);
            return true;
        } catch (\Exception $e) {
            return app_fail(9996);
        }
    }

    /**
     * 删除保护信息
     * User: zhouyao
     * Date: 2018/12/4
     * Time: 4:58 PM
     * @param $params
     * @return  mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delete($params)
    {
        if (empty($params) || !isset($params['guid']) || !isset($params['id'])) {
            return app_fail(9997);
        }

        $user = self::$userModel->where('id', '=', $params['guid'])->find();
        $row = self::$model->where('id', '=', $params['id'])->find();

//        if ($user->type != 1 && $row['user_id'] != $params['guid']) {
//            return app_fail(1000);
//        }

        try {
            self::$model->where('id', '=', $params['id'])->delete();
            self::$operateModel->where('res_code', '=', $row['res_code'])->delete();
            self::$templateModel->where('res_code', '=', $row['res_code'])->delete();
            return true;
        } catch (\Exception $e) {
            return app_fail(9980);
        }
    }

    /**
     * 显示所有保护
     * User: zhouyao
     * Date: 2018/12/7
     * Time: 3:30 PM
     * @param $params
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function protectAll($params)
    {
        $result = self::$model->field(['id', 'res_name'])->select();
        return $result;
    }

    /**
     * 获取当前用户能查看的保护
     * User: zhouyao
     * Date: 2018/12/9
     * Time: 11:16 AM
     * @param $params
     * @return mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function protectList($params)
    {
        if (empty($params) || !isset($params['limit']) || !isset($params['page'])) {
            return app_fail(9997);
        }

        $userInfo = self::$userModel->where(['id'=>$params['guid']])->find();
        $where = '';
        if($userInfo->type == 2)
        {
            $where1 = [
                ['user_id', '=', $params['guid']],
                ['res_code', '<>', 'null'],
            ];
            $res_code_arr = self::$operateModel->where($where1)
                ->distinct(true)
                ->field('res_code')
                ->page($params['page'], $params['limit'])
                ->column('res_code');
            $res_code_str = "'".implode("','", $res_code_arr)."'";
            $where = " res_code in ($res_code_str) or user_id = ".$params['guid'];
        }
        $count = self::$model->where($where)->count();
        if ($count < 1) {
            return ['data' => [], 'count' => (int) $count];
        }
        $result     = self::$model->where($where)->page($params['page'], $params['limit'])->select();
        $resultArr = $result->toArray();
        $stationArr = array_column($resultArr, 'station_id');
        $userArr    = array_column($resultArr, 'user_id');
        $station = self::$stationModel->whereIn('id', $stationArr)->column('station_name', 'id');
        $user    = self::$userModel->whereIn('id', $userArr)->column('nickname', 'id');

        $result->each(function ($item) use ($station, $user) {
            $item->station_name = isset($station[$item->station_id]) ? $station[$item->station_id] : '--';
            $item->nickname     = isset($user[$item->user_id]) ? $user[$item->user_id] : '--';
            $item->create_time  = date('Y-m-d', $item->create_time);
            return $item;
        });

        return ['data' => $result, 'count' => (int) $count];
    }

    /**
     * 获取指定变电站下的保护
     * User: zhouyao
     * Date: 2018/12/9
     * Time: 5:46 PM
     * @param $params
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @return mixed
     */
    public function stationOne($params)
    {
        if (empty($params)) {
            return app_fail(9997);
        }

        $result = self::$model->where(['station_id' => $params['station_id']])
            ->field(['res_code', 'res_name'])
            ->select();
        return $result;
    }

    /**
     * 显示保护模板
     * User: zhouyao
     * Date: 2018/12/9
     * Time: 5:57 PM
     * @param $params
     * @return  mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function protectTemp($params)
    {
        if (empty($params)) {
            return app_fail(9997);
        }

        $result = self::$templateModel->where(['res_code' => $params['res_code']])
            ->field(['id', 'template_name'])
            ->select();
        return $result;
    }



}